package com.xgp.Software.controller;

import com.xgp.Software.dto.GithubUser;
import com.xgp.Software.dto.QuestionDTO;
import com.xgp.Software.mapper.QuestionMapper;
import com.xgp.Software.mapper.UserMapper;
import com.xgp.Software.model.Question;
import com.xgp.Software.model.User;
import com.xgp.Software.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Action;

@Controller
public class PublishController {

    @Autowired
    private QuestionService questionService;

    @GetMapping("/publish/{id}")
    public String edit(@PathVariable(name = "id") Long id,Model model) {
        QuestionDTO question = questionService.getById(id);
        model.addAttribute("title",question.getTitle());
        model.addAttribute("description",question.getDescription());
        model.addAttribute("tag",question.getTag());
        model.addAttribute("id",question.getId());
        return "publish";
    }

    @GetMapping("/publish")
    public String publish() {
        return "publish";
    }

    @PostMapping("/publish")
    public String doPublish(
            @RequestParam("title") String title,
            @RequestParam("description") String description,
            @RequestParam("tag") String tag,
            @RequestParam(value = "id",required = false) Long id,
            HttpServletRequest request,
            Model model
    ) {

        model.addAttribute("title",title == null ? "" : title);
        model.addAttribute("description",description == null ? "" : description);
        model.addAttribute("tag",tag == null ? "" : tag);


        User user = (User) request.getSession().getAttribute("user");
        if(user == null) {
            model.addAttribute("error","用户未登陆");
            return "publish";
        }

        if(title == null || title == "") {
            model.addAttribute("error","标题不能为空");
            return "publish";

        }
        if(description == null || description == "") {
            model.addAttribute("error","内容不能为空");
            return "publish";
        }
        if(tag == null || tag == "") {
            model.addAttribute("error","标签不能为空");
            return "publish";
        }

        Question question = new Question();
        question.setTitle(title);
        question.setDescription(description);
        question.setTag(tag);
        question.setCreator(user.getId());

        question.setId(id);
        questionService.createOrUpdate(question);
//        questionSer.create(question);
        return "redirect:/";
    }
}
